﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using bdnt_pets_system.Tools;
using bdnt_pets_system_Entity;
using System.Globalization;

namespace bdnt_pets_system.MyUserControls
{
    public partial class MyComboBox : UserControl
    {
        public List<Tbl_DictInfo> ItemsSource
        {
            get
            {
                if (myCombox.ItemsSource is List<Tbl_DictInfo>)
                    return myCombox.ItemsSource as List<Tbl_DictInfo>;
                else return new List<Tbl_DictInfo>();
            }
        }

        public Tbl_DictInfo SelectedItem
        {
            get
            {
                if (ItemsSource.Count > 0)
                    return myCombox.SelectedItem as Tbl_DictInfo;
                else return null;
            }
        }

        public MyComboBox()
        {
            InitializeComponent();
            myCombox.DisplayMemberPath = SessionManager.IsCN_ZH ? "DictName" : "en_DictName";
            myCombox.SelectedValuePath = "DictValue";
        }

        #region 数据的加载
        /// <summary>
        /// 加载数据字典
        /// </summary>
        /// <param name="pid">父级字典id</param>
        /// <param name="currentValue">当前选中字典dictValue值</param>
        public void LoadDict(int pid, string currentValue)
        {
            //菜单类型
            if (DictInfoManager.LoadDictsByPId(pid))
            {
                var cuos = DictInfoManager.CurrentDicts.Distinct().ToList();
                myCombox.ItemsSource = cuos;
                var selectobj = cuos.FirstOrDefault(p => p.DictValue == currentValue);
                myCombox.SelectedIndex = selectobj == null ? 0 : cuos.IndexOf(selectobj);
            }
            else
            {
                SystemServiceReference.SystemServiceClient sysClient = new SystemServiceReference.SystemServiceClient();
                sysClient.GetDictListByPidCompleted += new EventHandler<SystemServiceReference.GetDictListByPidCompletedEventArgs>(sysClient_GetDictListByPidCompleted);
                sysClient.GetDictListByPidAsync(pid, currentValue);
                sysClient.CloseAsync();
            }
        }

        void sysClient_GetDictListByPidCompleted(object sender, SystemServiceReference.GetDictListByPidCompletedEventArgs e)
        {
            var cos = e.Result.OrderBy(p => p.Sequence).ToList();
            DictInfoManager.AddToAllDicts(cos);
            myCombox.ItemsSource = cos;
            var selectobj = cos.FirstOrDefault(p => p.DictValue == e.UserState.ToString());
            myCombox.SelectedIndex = selectobj == null ? 0 : cos.IndexOf(selectobj);
        }
        #endregion
    }
}
